<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="btns">
        <button data-path="/home">首页</button>
        <button data-path="/news">新闻</button>
        <button data-path="/amusement">娱乐</button>
    </div>
    <div class="content"></div>
    <script>
        const oBtns = document.querySelectorAll(".btns button")
        const oContent = document.querySelector(".content")
        // 1.设置一个路由表
        const routes = [{
            path: "/home",
            component: "我是首页"
        }, {
            path: "/news",
            component: "热点新闻"
        }, {
            path: "/amusement",
            component: "娱乐焦点"
        }]

        // 2.给按钮绑定点击事件
        for (let i = 0; i < oBtns.length; i++) {
            oBtns[i].onclick = function () {
                // console.log(this.dataset.path);
                //使用location.hash可以改变hash地址
                location.hash = this.dataset.path
            }
        }

        // 3.监听hash地址的改变，然后根据当前的hash地址和路由表对比，展示内容
        window.onhashchange = function (e) {
            // console.log(e);
            const newUrl = e.newURL.split("#")[1]
            // console.log(newUrl);
            const result = routes.find(item => item.path === newUrl)
            // console.log(result);
            oContent.innerHTML = result.component
        }
    </script>
</body>

</html>